package com.example.srb.sms.controller.api;

import com.example.srb.common.exception.Assert;
import com.example.srb.common.result.ResponseEnum;
import com.example.srb.common.result.Result;
import com.example.srb.common.util.RandomUtils;
import com.example.srb.common.util.RegexValidateUtils;
import com.example.srb.sms.client.CoreUserInfoClient;
import com.example.srb.sms.service.ApiSmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "短信管理")
@RequestMapping("/api/sms")
@Slf4j
//@CrossOrigin
public class ApiSmsController {

    @Autowired
    private ApiSmsService apiSmsService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CoreUserInfoClient coreUserInfoClient;

    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public Result send(@ApiParam(value = "手机号码",required = true)@PathVariable("mobile") String mobile){

        //校验手机是否为空
        Assert.notNull(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        //校验手机是否正确
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile),ResponseEnum.MOBILE_ERROR);

        //验证手机号是否被注册
        boolean flag = coreUserInfoClient.checkMobile(mobile);
        Assert.isTrue(flag == false, ResponseEnum.MOBILE_EXIST_ERROR);

        Map<String,Object> map = new HashMap<>();
        String code = RandomUtils.getFourBitRandom();
        map.put("code",code);
        //测试可以把阿里云关掉，免得浪费短信服务
        //apiSmsService.send(mobile, SmsProperties.TEMPLATE_CODE,map);

        //验证码存入redis
        redisTemplate.opsForValue().set("srb:sms:code:"+mobile,code,5, TimeUnit.MINUTES);
        return Result.ok().message("短信发送成功!");
    }
}
